package com.jinzhi.api.controller.aunt;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.api.service.AuntHomeService;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.AuntUserVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxpay.vo.R;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: mcf
 * @CreateTime: 2024/05/10
 * @Description: 阿姨端首页Controller
 */
@Controller
@RequestMapping("/api/auntHome")
@Api(value = "阿姨端首页", tags = "阿姨端首页")
public class AuntHomeController {

    private final JazSysBannerService jazSysBannerService;

    private final AuntHomeService auntHomeService;

    private final JazSysProjectService jazSysProjectService;

    private final JazMessageService jazMessageService;

    private final JazUserOrderService jazUserOrderService;

    private final JazUserDemandService jazUserDemandService;

    private final JazOrderTakingService jazOrderTakingService;

    @Autowired
    private UserService userService; //用户表
    @Autowired
    private JazUserAuntService jazUserAuntService; //月嫂表

    @Autowired
    private JazInterviewService jazInterviewService; //月嫂表



    public AuntHomeController(JazSysBannerService jazSysBannerService,AuntHomeService auntHomeService,JazSysProjectService jazSysProjectService,JazMessageService jazMessageService,JazUserOrderService jazUserOrderService,JazUserDemandService jazUserDemandService, JazOrderTakingService jazOrderTakingService){
        this.jazSysBannerService = jazSysBannerService;
        this.auntHomeService = auntHomeService;
        this.jazSysProjectService = jazSysProjectService;
        this.jazMessageService = jazMessageService;
        this.jazUserOrderService = jazUserOrderService;
        this.jazUserDemandService = jazUserDemandService;
        this.jazOrderTakingService  = jazOrderTakingService;
    }

    @ApiOperation(value = "banner轮播图", notes = "banner轮播图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "size", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "curren", value = "curren", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "position", value = "position", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/bannerList")
    public Result<List<JazSysBannerDO>> list(JazSysBannerDO jazSysBannerDTO){
        // 查询列表数据
        Wrapper<JazSysBannerDO> jazSysBannerDOWrapper = new EntityWrapper<JazSysBannerDO>().orderBy("sort", true).orderBy("id", false);
        if(null!=jazSysBannerDTO.getPosition()){
            jazSysBannerDOWrapper.eq("position",jazSysBannerDTO.getPosition());
        }
        List<JazSysBannerDO> list = jazSysBannerService.selectList(jazSysBannerDOWrapper);
        return Result.ok(list);
    }


    @ApiOperation(value = "需求分页列表查询", notes = "需求分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "服务类型id", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "age", value = "年龄", required = false, dataType = "String"),
            @ApiImplicitParam(name = "salary", value = "薪资待遇", required = false, dataType = "BigDecimal"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "curren", value = "当前页", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/selUserDemandList")
    public Result<?> selUserDemandList(String projectId,String age,String salary,int current, int size){

        return auntHomeService.selUserDemandList(projectId,age,salary,current,size);
    }


    /**
     * 月嫂入驻功能 阿姨招募提交接口
     * @param auntUserVO
     * @return
     */
    @ApiOperation(value = "月嫂入驻功能 阿姨招募提交接口", notes = "月嫂入驻功能 阿姨招募提交接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auntUserVO", value = "月嫂表单", required = true, dataType = "Object"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @PostMapping("/savaUserAunt")
    public Result<?> savaUserAunt(@RequestBody AuntUserVO auntUserVO) throws Exception{

        return auntHomeService.savaUserAunt(auntUserVO);
    }

    @ApiOperation(value = "阿姨首页主要服务查询  8个", notes = "阿姨首页主要服务查询 8个")
    @ApiImplicitParams({

    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/list")
    public Result<List<JazSysProjectDO>> list(){
        Wrapper<JazSysProjectDO> wrapper = new EntityWrapper<>();
        wrapper.eq("status",0); //正常状态
        wrapper.orderBy("sort");
        List<JazSysProjectDO> jazSysProjectDOS = jazSysProjectService.selectList(wrapper);
        jazSysProjectDOS =  jazSysProjectDOS.stream().limit(8).collect(Collectors.toList());  //只要前8个项目
        return Result.ok(jazSysProjectDOS);
    }


    /**
     * 需求详情查询
     * @return
     */
    @ApiOperation(value = "需求详情查询", notes = "需求详情查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求列表id", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = JazUserDemandDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/selUserDemandById")
    public Result<?> selUserDemandById(String id){

        return auntHomeService.selUserDemandById(id);
    }




    /**
     * 我要接单
     * @return
     */
    @PostMapping("/orderReceiving")
    @ResponseBody
    @Transactional
    public Result<?> orderReceiving(Long demandId){

        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(demandId); //查询出需求信息
        UserDO getUser = JWTUtil.getUser(); //获取当前登录的用户信息

        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("sys_userid",getUser.getId());
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(entityWrapper);

        String userAuntProjectId = jazUserAuntDO.getProjectId(); //1165599,56524466,4622466 逗号隔开
        Long projectId = jazUserDemandDO.getProjectId();

        if (!isProjectIdIncluded(userAuntProjectId,projectId)){
            return Result.fail("不能接不同类型的订单！");
        }

        if (jazUserAuntDO.getEnableStatus()==null){
            return Result.fail("未启用不状态下能接单");
        }

        if (jazUserAuntDO.getEnableStatus()==0){
            return Result.fail("未启用不状态下能接单");
        }


        EntityWrapper entityWrapper2 =new EntityWrapper();
        entityWrapper2.eq("signing_id",getUser.getId()); //签约人
        entityWrapper2.eq("status",0); //待开始
        List list = jazUserOrderService.selectList(entityWrapper2);

        if (list.size()>0){
            return Result.fail("您有待开始的合同订单，不能进行接单");
        }


        entityWrapper2 =new EntityWrapper();
        entityWrapper2.eq("signing_id",getUser.getId()); //签约人
        entityWrapper2.eq("status",1); //进行中
        list = jazUserOrderService.selectList(entityWrapper2);

        if (list.size()>0){
            return Result.fail("您有进行中的合同订单，不能进行接单");
        }



        Wrapper<JazOrderTakingDO> wrapper = new EntityWrapper<>();
        wrapper.eq("demand_id",demandId); //需求id
        wrapper.eq("invitee_id",getUser.getId()); //需求id
        if (jazOrderTakingService.selectOne(wrapper)!=null){
            return Result.fail("请勿重复预约");
        }


        //修改需求接单状态
        jazUserDemandDO.setStatus(2);
        jazUserDemandService.updateById(jazUserDemandDO);


        JazOrderTakingDO jazOrderTakingDO =new JazOrderTakingDO(); //创建接单表
        jazOrderTakingDO.setDemandId(jazUserDemandDO.getId()); //需求id
        jazOrderTakingDO.setInviteeId(getUser.getId()); //被邀约人id
        jazOrderTakingDO.setInviterId(jazUserDemandDO.getSysUserid()); //邀约人id
        jazOrderTakingDO.setCreateTime(new Date()); //创建时间
        jazOrderTakingDO.setInterviewStatus(1);//是否发起预约状态


        Long jazOrderTakingMax = jazOrderTakingService.selJazOrderTakingMax(); //查询出最大编号

        jazOrderTakingDO.setOrderNumber(generateOrderNumber(jazOrderTakingMax)); //订单编号

        jazOrderTakingService.insert(jazOrderTakingDO);

        Integer demandSource = jazUserDemandDO.getDemandSource();  //需求来源( 1 用户发布需求  2 后台发布需求)

        if (demandSource == 1){ //用户发布需求
            JazMessageDO jazMessageDO = new JazMessageDO();
            jazMessageDO.setSenderId(getUser.getId());
            jazMessageDO.setReceiverId(jazUserDemandDO.getSysUserid());
            jazMessageDO.setMessageType(2);
            jazMessageDO.setDemandId(jazUserDemandDO.getId());
            jazMessageDO.setAuntId(jazUserAuntDO.getId());
            jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_101.getMsg());
            jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_101.getNum());
            jazMessageDO.setHasSendSms(true); //发短信
            jazMessageService.senMessage(jazMessageDO);
        }


        return Result.ok();
    }


    public boolean isProjectIdIncluded(String userAuntProjectId, Long projectId) {
        // 将 userAuntProjectId 按逗号分隔成字符串数组
        String[] projectIdsArray = userAuntProjectId.split(",");

        // 将字符串数组转换成 Set，方便查找
        Set<String> projectIdsSet = new HashSet<>(Arrays.asList(projectIdsArray));

        // 将 projectId 转换成字符串
        String projectIdStr = String.valueOf(projectId);

        // 检查 Set 中是否包含 projectId
        return projectIdsSet.contains(projectIdStr);
    }



    /**
     * 是否预约接单
     * @return
     */
    @GetMapping("/isOrderReceiving")
    @ResponseBody
    public Result<?> isOrderReceiving(Long demandId){
        Wrapper<JazOrderTakingDO> wrapper = new EntityWrapper<>();
        wrapper.eq("demand_id",demandId); //需求id
        UserDO getUser = JWTUtil.getUser(); //获取当前登录的用户信息
        wrapper.eq("invitee_id",getUser.getId()); //需求id
        JazOrderTakingDO jazOrderTakingDO = jazOrderTakingService.selectOne(wrapper);
        if (jazOrderTakingDO!=null){
            return Result.ok(1);
        }
        return Result.ok(0);
    }




    /**
     * 查看已预约人数
     * @return
     */
    @GetMapping("/selOrderReceivingSum")
    @ResponseBody
    public Result<?> selOrderReceivingSum(Long demandId){
        Wrapper<JazOrderTakingDO> wrapper = new EntityWrapper<>();
        wrapper.eq("demand_id",demandId); //需求id
        List<JazOrderTakingDO> list = jazOrderTakingService.selectList(wrapper);
        int sum = 0;
        if (list != null){
            sum = list.size();
            sum = sum - 1;
        }
        return Result.ok(sum);
    }







    // 修改为返回 Long 类型的方法
    public Long generateOrderNumber(Long maxOrderNumber) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 格式化日期部分，年份后两位 + 月份 + 日
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyMMdd"));

        // 如果 maxOrderNumber 为 null，表示没有查询到最大编号，则从 1 开始
        long newNumber = 1L;
        if (maxOrderNumber != null) {
            // 获取最大编号的日期部分
            String maxOrderNumberStr = String.valueOf(maxOrderNumber);
            String maxDatePart = maxOrderNumberStr.substring(0, 6); // 假设编号的前六位是日期部分

            // 如果最大编号的日期和当前日期相同，则在原有基础上递增
            if (maxDatePart.equals(datePart)) {
                long maxNumber = Long.parseLong(maxOrderNumberStr.substring(6)); // 获取序号部分
                newNumber = maxNumber + 1;
            }
        }

        // 查询用户 sh



        // 拼接成完整的订单编号
        Long orderNumber = Long.parseLong(datePart + String.format("%04d", newNumber));
        return orderNumber;
    }






    /**
     * 查询已预约月嫂列表
     * @return
     */
    @GetMapping("/selMakeAunt")
    @ResponseBody
    public Result<?> selMakeAunt(Long demandId){

        Wrapper<JazOrderTakingDO> wrapper = new EntityWrapper<>();
        wrapper.eq("demand_id",demandId); //需求id

        List<JazOrderTakingDO> list = jazOrderTakingService.selectList(wrapper);

        for (int i=0;i<list.size();i++){
            Long inviteeId = list.get(i).getInviteeId(); //被邀约人id

            EntityWrapper<JazUserAuntDO> inviteeWrapper = new EntityWrapper<JazUserAuntDO>();
            inviteeWrapper.eq("sys_userid",inviteeId);
            JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(inviteeWrapper);

            UserDO userDO = userService.selectById(inviteeId);

            list.get(i).setAuntUserId(jazUserAuntDO.getId()); //月嫂id
            list.get(i).setName(userDO.getName()); //月嫂名字
            list.get(i).setInchPhoto(userDO.getHeadPortrait()); //头像



            Wrapper<JazInterviewDO> inviteStatusWrapper = new EntityWrapper<>();
            inviteStatusWrapper.eq("demand_id",demandId); //需求id
            inviteStatusWrapper.eq("invitee_id",inviteeId); //被邀约人id
            if (jazInterviewService.selectOne(inviteStatusWrapper)!=null){
                list.get(i).setInviteStatus(1); //已邀约
            }else {
                list.get(i).setInviteStatus(0); //未邀约
            }

        }

        return Result.ok(list);
    }







    /**
     * 审核状态查询
     * @return
     */
    @ApiOperation(value = "审核状态查询", notes = "审核状态查询")
    @ApiImplicitParams({

    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/isUserAunt")
    public Result<?> isUserAunt(){

        return auntHomeService.isUserAunt();
    }


    /**
     * 判断是否签约
     * auntId：月嫂id
     * @return
     */
    @ApiOperation(value = "判断是否签约", notes = "判断是否签约")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auntUserId", value = "月嫂id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "senderId", value = "消息发送者id（接单人id）", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "receiverId", value = "消息接收者id（sysUserId）", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "demandId", value = "媒介id（需求id）", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = JazUserOrderDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/isContract")
    public Result<?> isContract(String auntUserId,Long senderId,Long receiverId,Long demandId){


        return auntHomeService.isContract(auntUserId,senderId,receiverId,demandId);
    }

    /**
     *
     * 我要接单（发送接单消息给用户端）
     * @return
     */
    @ApiOperation(value = "我要接单（发送接单消息给用户端）", notes = "我要接单（发送接单消息给用户端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "senderId", value = "消息发送者id（接单人id）", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "receiverId", value = "消息接收者id（sysUserId）", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "objectId", value = "媒介id（需求id）", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = JazMessageDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/takingOrders")
    @Transactional
    public Result<?> takingOrders(Long senderId,Long receiverId,Long objectId){

        return auntHomeService.takingOrders(senderId,receiverId,objectId);
    }

    /**
     * 月嫂简历信息回显
     * @return
     */
    @ApiOperation(value = "月嫂简历信息回显", notes = "月嫂简历信息回显")
    @ApiImplicitParams({

    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = AuntUserVO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/selUserAunt")
    public Result<?> selUserAunt(){

        return auntHomeService.selUserAunt();
    }

    /**
     * 可用标签下拉框查询
     * @return
     */
    @ApiOperation(value = "可用标签下拉框查询", notes = "可用标签下拉框查询")
    @ApiImplicitParams({

    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = JazSysLabelDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/sleLabel")
    public Result<?> sleLabel(){
        return auntHomeService.sleLabel();
    }


    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = UserDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(String token){

        return auntHomeService.getUserInfo(token);
    }

    /**
     * 判断阿姨招募是否能填写
     * true:可以
     * false:不可以
     * @return
     */
    @ApiOperation(value = "判断阿姨招募是否能填写(true:可以,false:不可以)", notes = "判断阿姨招募是否能填写(true:可以,false:不可以)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auntId", value = "阿姨id", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = UserDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/getIsEdit")
    public Result<?> getIsEdit(Long auntId){

        return auntHomeService.getIsEdit(auntId);
    }


    /**
     * 阿姨端查询订单详情
     * @return
     */
    @ApiOperation(value = "阿姨端查询订单详情", notes = "阿姨端查询订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = UserDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/auntOrderDetail")
    public Result<?> auntOrderDetail(Long id){

        return Result.ok(jazUserOrderService.auntOrderDetail(id));
    }



    @ApiOperation(value = "批量新增阿姨", notes = "批量新增阿姨")
    @ApiImplicitParams({
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功",response = UserDO.class),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping("/addAunt")
    public Result<?> addAunt(){

        auntHomeService.addAunt();
        return Result.ok();
    }






}
